package com.ruoyi.pharmacy.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.pharmacy.domain.PharmacyDrugStock;
import com.ruoyi.pharmacy.domain.vo.PharmacyOperateVo;
import com.ruoyi.pharmacy.mapper.PharmacyDrugStockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.pharmacy.mapper.PharmacyOperateMapper;
import com.ruoyi.pharmacy.domain.PharmacyOperate;
import com.ruoyi.pharmacy.service.IPharmacyOperateService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 药房操作记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-22
 */
@Service
public class PharmacyOperateServiceImpl implements IPharmacyOperateService
{
    @Autowired
    private PharmacyOperateMapper pharmacyOperateMapper;
    @Autowired
    private PharmacyDrugStockMapper pharmacyDrugStockMapper;

    /**
     * 查询药房操作记录
     *
     * @param operateId 药房操作记录主键
     * @return 药房操作记录
     */
    @Override
    public PharmacyOperate selectPharmacyOperateByOperateId(Integer operateId)
    {
        return pharmacyOperateMapper.selectPharmacyOperateByOperateId(operateId);
    }

    /**
     * 查询药房操作记录列表
     *
     * @param pharmacyOperate 药房操作记录
     * @return 药房操作记录
     */
    @Override
    public List<PharmacyOperate> selectPharmacyOperateList(PharmacyOperate pharmacyOperate)
    {
        return pharmacyOperateMapper.selectPharmacyOperateList(pharmacyOperate);
    }

    //查询药房操作记录列表 除了原有字段 需要查询药品名字 药房名字
    @Override
    public List<PharmacyOperateVo> selectPharmacyOperateVoList(PharmacyOperate pharmacyOperate) {
        return pharmacyOperateMapper.selectPharmacyOperateVoList(pharmacyOperate);
    }

    /**
     * 新增药房操作记录
     *
     * @param pharmacyOperate 药房操作记录
     * @return 结果
     */
    @Override
    public int insertPharmacyOperate(PharmacyOperate pharmacyOperate)
    {
        return pharmacyOperateMapper.insertPharmacyOperate(pharmacyOperate);
    }

    /**
     * 修改药房操作记录
     *
     * @param pharmacyOperate 药房操作记录
     * @return 结果
     */
    @Override
    public int updatePharmacyOperate(PharmacyOperate pharmacyOperate)
    {
        return pharmacyOperateMapper.updatePharmacyOperate(pharmacyOperate);
    }

    /**
     * 批量删除药房操作记录
     *
     * @param operateIds 需要删除的药房操作记录主键
     * @return 结果
     */
    @Override
    public int deletePharmacyOperateByOperateIds(Integer[] operateIds)
    {
        return pharmacyOperateMapper.deletePharmacyOperateByOperateIds(operateIds);
    }

    /**
     * 删除药房操作记录信息
     *
     * @param operateId 药房操作记录主键
     * @return 结果
     */
    @Override
    public int deletePharmacyOperateByOperateId(Integer operateId)
    {
        return pharmacyOperateMapper.deletePharmacyOperateByOperateId(operateId);
    }
    /**
     *  新增操作记录并更新库存
     */

    @Transactional
    public AjaxResult addOperateAndUpdateStock(PharmacyOperate pharmacyOperate ){
        int totalAffected = 0; // 总受影响行数
        // 1. 解析参数（注意：避免空指针，建议先判空）
//        if (pharmacyOperate == null
//                || pharmacyOperate.getDrugId() == null
//                || pharmacyOperate.getPharmacyId() == null
//                || pharmacyOperate.getQuantity() == null

//                || pharmacyOperate.getOperateType() == null
//                || pharmacyOperate.getRelatedId() == null
//        ) {
//            return AjaxResult.error("参数不完整，请检查药房ID、药品ID、数量、操作类型、关联id");
//        }

        Long drugId = Long.valueOf(pharmacyOperate.getDrugId());
        Long pharmacyId = Long.valueOf(pharmacyOperate.getPharmacyId());
        Long quantity = Long.valueOf(pharmacyOperate.getQuantity());
//        Long transferId = Long.valueOf(pharmacyOperate.getRelatedId());
        Integer operateType = pharmacyOperate.getOperateType();
//        String remark = pharmacyOperate.getRemark();

        //新增一条药房操作记录
         int operateAffected =  pharmacyOperateMapper.insertPharmacyOperate(pharmacyOperate);
         totalAffected += operateAffected;

        //根据药品id和药房id查询库存
        Long stock =pharmacyDrugStockMapper.queryStockByPharmacyIdAndDrugId(pharmacyId,drugId);
        if(stock==null){ //添加一条库存
            // 3.1 库存不存在：新增库存（仅调拨入库允许，取药不允许新增空库存）
            if (operateType == 1) {
                // 调拨入库：允许新增库存
                PharmacyDrugStock newDrugStock = new PharmacyDrugStock();
                newDrugStock.setPharmacyId(Math.toIntExact(pharmacyId));
                newDrugStock.setDrugId(Math.toIntExact(drugId));
                newDrugStock.setQuantity(Math.toIntExact(quantity));
                newDrugStock.setLastUpdateTime(new Date());
                Random random = new Random();
                // 1-10
                int baseNum = random.nextInt(10) + 1;
                //10-100
                int minQty = baseNum * 10;
                newDrugStock.setMinQuantity(minQty);
                int stockAffected = pharmacyDrugStockMapper.insertPharmacyDrugStock(newDrugStock);
                totalAffected += stockAffected;
            } else {
                // 取药出库：库存不存在（相当于库存为0），直接返回错误
                return AjaxResult.error("取药失败：当前药房无该药品库存，无法取药");
            }
        }else{ //更新操作  1=调拨 2=取药
            // 3.2 库存存在：更新库存（核心：取药时校验库存）
            int newQuantity = 0;
            if (operateType == 1) {
                // 调拨入库：库存增加（无需校验，直接累加）
                newQuantity = Math.toIntExact(stock + quantity);
            } else if (operateType == 2) {
                // 取药出库：关键校验——库存必须大于操作数量
                if (stock <= quantity) {
                    // 库存不足：返回错误，不执行更新
                    return AjaxResult.error("取药失败：当前库存为" + stock + "，需取药" + quantity + "，库存不足");
                }
                // 库存充足：计算新库存
                newQuantity = Math.toIntExact(stock - quantity);
            } else {
                // 操作类型非法（非1/2）
                return AjaxResult.error("操作类型错误：仅支持1（调拨入库）、2（取药出库）");
            }
            // 执行库存更新（确保SQL条件包含 pharmacyId 和 drugId）
            PharmacyDrugStock updateStock = new PharmacyDrugStock();
            updateStock.setPharmacyId(Math.toIntExact(pharmacyId));
            updateStock.setDrugId(Math.toIntExact(drugId));
            updateStock.setQuantity(newQuantity);
            updateStock.setLastUpdateTime(new Date());
            int stockAffected = pharmacyDrugStockMapper.updatePharmacyDrugStockQuantity(updateStock);
            totalAffected += stockAffected;
        }
        return AjaxResult.success("操作成功", totalAffected);
    }
}
